package Pet.Management.controller;

import Pet.Management.common.utils.JwtUtils;
import Pet.Management.domain.entity.User;
import Pet.Management.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system/user/profile")
@RequiredArgsConstructor
@CrossOrigin
public class UserProfileController {

    private final UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取当前登录用户个人信息
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getProfile(@RequestHeader("Authorization") String token) {
        // 从token中获取当前用户ID
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = jwtUtils.getUserIdFromToken(token);
        User user = userService.getById(userId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "操作成功");
        response.put("data", user);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 更新用户个人信息
     */
    @PutMapping
    public ResponseEntity<Map<String, Object>> updateProfile(@RequestHeader("Authorization") String token, 
                                                         @RequestBody User userParam) {
        // 从token中获取当前用户ID
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = jwtUtils.getUserIdFromToken(token);
        User user = userService.getById(userId);
        
        // 只允许更新部分字段
        if (userParam.getNickname() != null) {
            user.setNickname(userParam.getNickname());
        }
        if (userParam.getEmail() != null) {
            user.setEmail(userParam.getEmail());
        }
        if (userParam.getPhone() != null) {
            user.setPhone(userParam.getPhone());
        }
        if (userParam.getSex() != null) {
            user.setSex(userParam.getSex());
        }
        if (userParam.getIdCard() != null) {
            user.setIdCard(userParam.getIdCard());
        }
        
        // 保存更新后的用户
        userService.updateUser(user);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        
        return ResponseEntity.ok(response);
    }
} 